package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.heima.article.dao.ApArticleConfigDao;
import com.heima.article.dao.ApArticleContentDao;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.model.article.entity.ApArticle;
import com.heima.article.dao.ApArticleDao;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.entity.ApArticleConfig;
import com.heima.model.article.entity.ApArticleContent;
import com.heima.model.articleDto.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.ArticleContants;
import com.heima.model.kafka.message.KafkaMessageConstants;
import com.heima.model.searchVo.SearchArticleVo;
import com.heima.model.userDto.ArticleHomeDto;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.utils.common.SnowflakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * 文章基础信息表(ApArticle)表服务实现类
 *
 * @author makejava
 * @since 2022-04-16 18:02:08
 */
@Service("apArticleService")
public class ApArticleServiceImpl implements ApArticleService {
    @Resource
    private ApArticleDao apArticleDao;
    @Resource
    private ApArticleConfigDao apArticleConfigDao;
    @Resource
    private ApArticleContentDao apArticleContentDao;
    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    private ApArticleFreemarkerService apArticleFreemarkerService;
    @Resource
    private KafkaTemplate kafkaTemplate;
    /**
     * 发布文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Long> save(ArticleDto dto) throws InvocationTargetException, IllegalAccessException {
        //校验参数是否为空  文章标题是否为空  文章id是否为空
        if (dto.getTitle() == null||dto==null||dto.getNewsId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //数据拷贝
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //判断这个请求 是修改请求 还是新增请求  根据newsId查询自媒体文章
       ApArticle article= apArticleDao.queryByNewsId(dto.getNewsId());
        if (article == null) {
           //新增需要用雪花算法算出id 将一张表的数据分三张所以不能有相同id
           //添加基本信息表
            //  channelName频道昵称 authorName作者昵称 layout文章布局类型
            apArticle.setId(snowflakeIdWorker.nextId());
            apArticle.setPublishTime(new Date());
            apArticleDao.insert(apArticle);
            //添加配置信息表
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(apArticle.getId());
            config.setCreatedTime(new Date());
            config.setUpdatedTime(new Date());
            apArticleConfigDao.insert(config);
            //添加文本内容表
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            content.setCreatedTime(new Date());
            content.setUpdatedTime(new Date());
            apArticleContentDao.insert(content);

        }else {
           //如果是修改 添加两张表数据
            //添加基本信息表
            apArticle.setId(article.getId());
            apArticle.setPublishTime(new Date());
            apArticle.setCreatedTime(new Date());
            apArticle.setUpdatedTime(new Date());
            apArticleDao.update(apArticle);
            //添加文本内容表
            ApArticleContent content = apArticleContentDao.queryById(article.getId());
            content.setContent(dto.getContent());
            content.setCreatedTime(new Date());
            content.setUpdatedTime(new Date());
            apArticleContentDao.update(content);
       }
        String url = apArticleFreemarkerService.buildArticle2Minio(apArticle.getId(), dto.getContent());
        //同步数据到es
        if (StringUtils.isEmpty(url)){
            throw new RuntimeException("生成文章静态详情页失败");
        }

        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, searchArticleVo);
        searchArticleVo.setContent(dto.getContent());
        searchArticleVo.setStaticUrl(url);

        kafkaTemplate.send(KafkaMessageConstants.AP_ARTICLE_ES_SYNC_TOPIC, toJSONString(searchArticleVo));
        return ResponseResult.okResult(apArticle.getId());
    }

    //加载首页 //**加载更多** //**加载最新**
    @Override
    public ResponseResult load(ArticleHomeDto dto,short loadType) {
        Integer size = dto.getSize();
        if (size == 0 && size==null) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(size,50));//不得超过五十条
        //判断时间是否为空
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleContants.DEFAULT_TAG);
        }
        Map<String, Object> map = BeanUtil.beanToMap(dto);
        map.put("loadType",loadType);

       List<ApArticle> apArticles= apArticleDao.load(map);

        return ResponseResult.okResult(apArticles);
    }

}
